import axios from 'axios';
import Router from 'vue-router';
import { Toast } from 'vant';
import {getCode} from './login.js'


axios.defaults.headers.post['Content-Type'] = 'application/json'
//axios.defaults.baseURL = 'http://uiapi.qicubao.com/'
//axios.defaults.baseURL = 'http://uiapi.taijizhigen.com/'
axios.defaults.baseURL = '/'

//window.localStorage.setItem("token","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJPcGVuSWQiOiJvSktTbXZ5TGc0anhNUWtlYVFvZ0cwdkFmU0RnIiwiVXNlcklkIjoiMSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvZXhwaXJhdGlvbiI6IjIwMjYvMi8xNCAwOjQzOjU5IiwibmJmIjoxNTkxMDAxMDM5LCJleHAiOjE3NzEwMDEwMzksImlzcyI6InpqbDIiLCJhdWQiOiJldmVyeW9uZSJ9.gGfX9n4pJq5dBJ6Icb2slFkcQ5oGTtWz8ZZ7suP9mWo");
let token=window.localStorage.getItem('token') 

let access_token='Bearer '+token    
axios.defaults.headers.common[ 'Authorization']=access_token
axios.defaults.headers.delete[ 'Authorization']=access_token

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
　　// 在发送请求之前做些什么
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    });
　　return config
}, function (error) {
　　// 对请求错误做些什么
  return Promise.reject(error)
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  console.log(response);
　　// 对响应数据做点什么
Toast.clear()
　　return response
}, function (error) {
  //console.log(error);
  //console.log(error.response);
  //Toast.clear()
  //  switch(error && error.response.status){
  //  	 case 400: error.message=error.response.data.ErrorMsg.ErrMsg;break;
  //    case 401: error.message='登录过期，请重新登录！';break;
  //  }
    if(error && error.response.status==401){
        window.localStorage.removeItem('token');
        console.log(Router);
        //getCode(Router.app._route.path,Router.app._route.query)
        getCode()
    }else if(error && error.response.status==400){
      console.log(99999);
      console.log(error.response.data.errMsg);
      console.log(99999);
      Toast({
        type:'fail',
        message:error.response.data.errMsg,
        duration:3000
      });
    }else{
      Toast(error.response.data.errMsg);
    }
})

//轮播图
export const BannerListUrl = (params) => axios.get('/api/Banner/List',params);
export const bbCreateQR = (params) => axios.get('/api/Member/CreateQR?url='+params);//生成推广二维码
export const getUrlKey = (name,url)=>{
　　return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null
}


export const loginajax = (url, data={}, type='GET') => {

    return new Promise(function (resolve, reject) {
      // 执行异步ajax请求
      let promise
      if (type === 'GET') {
        // 准备url query参数数据
        let dataStr = '' //数据拼接字符串
        Object.keys(data).forEach(key => {
          dataStr += key + '=' + data[key] + '&'
        })
        if (dataStr !== '') {
          dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
          url = url + '?' + dataStr
        }
        // 发送get请求
        promise = axios.get(url,{
          headers: {
            'Authorization':"Bearer " + localStorage.getItem('token')
          }})
      } else if (type === 'DELETE') {
        // 准备url query参数数据
        let dataStr = '' //数据拼接字符串
        Object.keys(data).forEach(key => {
          dataStr += key + '=' + data[key] + '&'
        })
        if (dataStr !== '') {
          dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
          url = url + '?' + dataStr
        }
        // 发送DELETE请求
        promise = axios.delete({
          url: url,
          data: data,
        })
      }else {
        // 发送post请求
        promise = axios.post(url, data,{
          headers: {
            'Authorization':"Bearer " + localStorage.getItem('token')
          }})
      }
      promise.then(function (response) {
        // 成功了调用resolve()
        console.log(response);
        resolve(response && response.data)
      }).catch(function (error) {
        //失败了调用reject()
        console.log(error);
        error = JSON.stringify(error);
        var reg = RegExp(/401/);
        if(error.match(reg)){
          // Router.push({
          //   path:'/login'
          // });
          return;
        }
        reject(error)
      })
    })
};

export const TraderListUrl = (params) => { return loginajax("/api/Trader/List", params) };
export const TraderDetailUrl = (params) => { return loginajax("/api/Trader/Detail", params) };
export const CashoutAddUrl = (params) => { return loginajax("/api/Cashout/Add", params, "POST") };
export const RechargePayUrl = (params) => axios.post("/api/Recharge/Pay?money="+params);
export const ConsumeListUrl = (params) => { return loginajax("/api/Member/ConsumeList", params) };//我的账单
export const MemberEditUrl = (params) => { return loginajax("/api/Member/Edit", params, "POST") };
export const MySonMemberUrl = (params) => { return loginajax("/api/Member/MySonMember", params) };//我的直接推荐
export const CityListUrl = (params) => { return loginajax("/api/City/List", params) };//城市列表
export const CityDetailUrl = (params) => { return loginajax("/api/City/Detail", params) };//城市列表详情
export const MapAddressUrl = (params) => { return loginajax("/api/City/MapAddress", params) };//根据经纬度获取位置
export const TraderCityListUrl = (params) => { return loginajax("/api/Trader/CityList", params) };//城市列表
export const MapCityListUrl = (params) => { return loginajax("/api/City/MapCity", params) };//获取地图经纬度城市
export const SiteConfigDetailUrl = (params) => { return loginajax("/api/SiteConfig/Detail", params) };///api/SiteConfig/Detail
export const TraderTypeListUrl = (params) => { return loginajax("/api/Trader/TraderType", params) };//商家类别
export const MemberBaseInfoUrl = (params) => { return loginajax("/api/Member/BaseInfo", params) };//商家类别

